from flask import Blueprint, request
from sqlalchemy import desc
from entity.Response import success,error,authority
from entity.Info import Info
from controller.LoginController import jwt_secret_key
from db import db
import oss2
import jwt


infoController = Blueprint('infoController',__name__)

auth = oss2.Auth('LTAI5tSXK6NrNBRRKMREWogX', 'VtNmUW6TZt1oJpYskBizw6u0p8bUXw')
bucket = oss2.Bucket(auth,'oss-cn-beijing.aliyuncs.com', 'fundusdetection')

"""
添加一条患者信息
input:
患者相关信息
output:
none
"""
@infoController.route('/submitInfo',methods=['POST'])
def submitInfo():
    age = request.get_json().get('age')
    gender = request.get_json().get('gender')
    description = request.get_json().get('description')
    leftFundus = request.get_json().get('leftFundus')
    rightFundus = request.get_json().get('rightFundus')
    result = request.get_json().get('result')
    username = request.get_json().get('username')

    info = Info(age=age,gender=gender,description=description,left_fundus=leftFundus,right_fundus=rightFundus,
                result=result,username=username)

    db.session.add(info)
    db.session.commit()

    return success(message='信息提交成功')

"""
input:
获取当前疾病距离现在最近的前k条数据
output:
数据List
"""
@infoController.route('/getTopKCase',methods=['GET'])
def getTopKCase():
    disaseType = request.args.get('type')
    k = request.args.get('k')
    
    infoList = Info.query.filter(Info.result.contains(disaseType)).order_by(desc(Info.create_time)).limit(k).all()
    dictList = []
    for info in infoList:
        dictList.append(info.to_dict())
    return success(message='相似病例查询成功',data=dictList)


"""
将文件上传至阿里云
input:
图像文件
output:
oss link
"""
@infoController.route('/imageToOSS', methods=['POST'])
def imageToOSS():
    if 'file' not in request.files:
        return error(message='文件不存在')

    imageFile = request.files['file']
    # 上传到的 OSS 路径
    oss_path = imageFile.filename
    bucket.put_object(oss_path, imageFile)

    # 设置对象为公开读权限
    bucket.put_object_acl(oss_path, oss2.OBJECT_ACL_PUBLIC_READ)

    # 生成永久有效的访问链接
    share_link = f"https://{bucket.bucket_name}.oss-cn-beijing.aliyuncs.com/{oss_path}"

    return success(message='上传成功', data=share_link)

"""
将多个文件上传至阿里云
input:
图像文件
output:
oss link
"""
@infoController.route('/batchImageToOSS', methods=['POST'])
def batchImageToOSS():
    if 'files' not in request.files:
        return error(message='文件不存在')

    imageFiles = request.files.getlist('files')
    links = []
    for imageFile in imageFiles:
        # 上传到的 OSS 路径
        oss_path = imageFile.filename
        bucket.put_object(oss_path, imageFile)

        # 设置对象为公开读权限
        bucket.put_object_acl(oss_path, oss2.OBJECT_ACL_PUBLIC_READ)

        # 生成永久有效的访问链接
        share_link = f"https://{bucket.bucket_name}.oss-cn-beijing.aliyuncs.com/{oss_path}"

        links.append(share_link)

    return success(message='上传成功', data=links)

"""
根据用户名获取用户的诊断记录
input:
none
output:
诊断记录List
"""
@infoController.route('/getDiagnosisHistory',methods=['GET'])
def getDiagnosisHistory():
    # 解析token拿到用户名
    # 获取token
    token = request.cookies.get('token')
    if not token:
        token = request.headers.get('token')
    if not token:
        return authority(message='鉴权失败，请先登录！')

    # 校验token
    try:
        decoded_payload = jwt.decode(token, jwt_secret_key, algorithms=['HS256'])
    except jwt.ExpiredSignatureError:
        return authority(message='token已过期，请重新登录！')
    except jwt.InvalidTokenError:
        return authority(message='无效token')

    username = decoded_payload['username']
    historyList = Info.query.filter_by(username=username).order_by(desc(Info.create_time))
    dataList = []
    for history in historyList:
        dataList.append(history.to_dict())
    return success(message='查询成功',data=dataList)